<?php

namespace baidu;

use Psr\Log\LoggerInterface;
use ShidianUtil\Net\IHttpClient;
use ShidianUtil\Utils\ConvertUtil;
use think\facade\Config;

/**
 * 百度 API回传
 * Class Ocpc
 * @package baidu
 */
class Ocpc
{
    private $httpClient;
    private $logger;

    /**
     * @param IHttpClient $httpClient
     * @param LoggerInterface $logger
     */
    public function __construct(IHttpClient $httpClient, LoggerInterface $logger)
    {
        $this->httpClient = $httpClient;
        $this->logger = $logger;
    }

    /**
     * API回传
     * @param $token
     * @param $logidUrl
     * @param $newType
     * @return OcpcResponse
     */
    public function uploadConvertData($token, $logidUrl, $newType): OcpcResponse
    {
        $uri = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';

        $conversionTypes = [
            [
                'logidUrl' => $logidUrl,
                'newType' => $newType,
            ]
        ];

        $post = [
            'token' => $token,
            'conversionTypes' => $conversionTypes
        ];

        $response = $this->httpClient->postJSONFormat($uri, [], [], $post);

        $body = $response->getBody()->__toString();

        if ($response->getStatusCode() != 200) {
            $this->logger->error('百度营销API回传HTTP状态码异常，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
            return new OcpcResponse($response, false, []);
        }

        $data = [];

        try {
            $data = ConvertUtil::jsonDecode($body);

            $status = $data['header']['status'] ?? null;
            if ($status === 0 || $status === '0') {
                $this->logger->info('百度营销API回传正常，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
                return new OcpcResponse($response, true, $data);
            }

            $this->logger->error('百度营销API回传接口响应码错误，响应{body},请求体{post}', ['body' => $body, 'post' => ConvertUtil::jsonEncode($post)]);
            return new OcpcResponse($response, false, $data);
        } catch (\Throwable $throwable) {

            $this->logger->error('百度营销API回传接口异常，原因{message}', ['message' => $throwable->getMessage()]);
            return new OcpcResponse($response, false, $data);
        }
    }


}
